<template>
    <div class="page">
        <Header :title="isFromForgetting?'防遗忘包': '标签选点'" left-arrow />
        <div class="content">
            <selected-tags
                ref="selectedTagRef" :citys="citys" :people-tags="peopleTags" :preference-tags="preferenceTags"
                :current-check-obj-tags="currentCheckObjTags"
                @changeCity="changeCity"
            ></selected-tags>

            <put-strategy ref="putStrategyRef" :is-from-forgetting="isFromForgetting" class="mt12" @on-tab-change="onTabChange" @changeData="strategyChange"></put-strategy>
        </div>
        <div class="bottom">
            <div class="bottom-text">
                <div v-if="isCommunity" class="family-box">
                    投放{{ numberWithCommas(screenPointNum) }}个智能屏，{{ numberWithCommas(lcdPointNum) }}个LCD，覆盖{{ numberWithCommas(people) }}人
                </div>
                <div class="total-amount">
                    <span v-if="isCommunity" class="amount">¥{{ formatNumber(price) }}</span>
                    <span v-else class="amount">-</span>
                    <span>（按刊例价的0.5折计算）</span>
                </div>
                <div class="cph-price">
                    <!-- <div v-if="isCommunity" class="family-box">
                        <span>覆盖家庭：</span>
                        <label class="family-num">{{ numberWithCommas(faimaly) }}</label>
                    </div> -->
                    <div v-if="isCommunity">
                        <span>CPH：</span>
                        <span class="price">
                            <template v-if="+faimaly === 0">--</template>
                            <template v-else>
                                {{ cph.value }}元/户/周
                            </template>
                        </span>
                    <!-- <van-popover v-model:show="showPopover" theme="dark" placement="top-end">
                        <div class="pop-content">
                            仅针对住宅类楼盘计算每户每周触达成本，您的投放策略覆盖{{ cph.premisesNum }}个中高端住宅楼盘，其中{{ cph.screenPointNum }}个智能屏，{{ cph.lcdPointNum }}个LCD
                        </div>
                        <template #reference>
                            <img src="@/assets/img/cph-tips.png" alt="">
                        </template>
                    </van-popover> -->
                    </div>
                </div>
            </div>

            <div class="fe-btns">
                <div class="left" @click="goBack">
                    上一步
                </div>
                <div class="right" :class="!isCommunity && 'disabled'" @click="nextStep">
                    下一步
                </div>
            </div>
        </div>
    </div>
</template>

<script name="productsSelectByTagStrategyCheck" lang="ts" setup>
import { ref, reactive } from 'vue';
import { store } from '@/store';
import { useRoute, useRouter } from 'vue-router';
import Header from '@/components/Header/index.vue';
import PutStrategy from '@/views/products/selectByTag/components/PutStrategy.vue';
import SelectedTags from '@/views/products/selectByTag/components/SelectedTags.vue';
import { Toast } from 'vant';
import { numberWithCommas, formatNumber } from '@/utils/filters';
import { TreeChildModel } from '@/views/products/selectByTag/selectByTag.module';
import { MediaItem, StrategyItemData, cityModel, peopleModel, StrategyResultData } from '@/views/products/selectByTag/strategy.module';
import { StrategyStatisticsReq, strategySpecsItem, getStrategyStatistics, saveStrategySpecs } from '@/api/brandBreakout';
import { clearLoading, showLoading } from '@/api';

const router = useRouter();
const route = useRoute();
const isFromForgetting = ref(+(route.query.isFromForgetting as string) === 1);
const projectId: string = store.state.app.home.projectId || '';
const selectByTag = store.state.app.selectByTag;
const citysAll = selectByTag?.checkedCityData as unknown as TreeChildModel[];
const citys:cityModel[] = citysAll.map(item => {
    return {
        tgCode: item.tgCode || item.id,
        name: item.name,
    };
});
const peopleTags = selectByTag?.customTag as unknown as peopleModel[];
const preferenceTags = selectByTag?.preference || [];
const currentCheckObjTags = selectByTag?.currentCheckObjTag as unknown as peopleModel[];
console.log(currentCheckObjTags);
// const showPopover = ref(false);
const selectedTagRef = ref({cityList: ''});
const putStrategyRef = ref({mediaTypes: {}, strategyList: {} });

let cityCodes = citys.map((item:cityModel) => (item.tgCode || item.id).toString()); // 城市code
let mediaTypes: number[] = []; // 媒体类型
let strategySpecs: StrategyItemData[] = [];

const price = ref('0');
const faimaly = ref(0);
const people = ref(0);
const screenPointNum = ref(0);
const lcdPointNum = ref(0);
let cph: StrategyResultData = reactive({
    framePointNum: 0,
    lcdPointNum: 0,
    premisesNum: 0,
    screenPointNum: 0,
    value: 0,
});

function resetData() {
    price.value = '0';
    cph = {
        framePointNum: 0,
        lcdPointNum: 0,
        premisesNum: 0,
        screenPointNum: 0,
        value: 0,
    };
    faimaly.value = 0;
    people.value = 0;
    screenPointNum.value = 0;
    lcdPointNum.value = 0;
}
// 获取投放策略信息
async function getStrategyStatisticInfo() {
    if(!mediaTypes.length) {
        resetData();
        return Toast.fail('媒体形式至少选择一种');
    }
    const params: StrategyStatisticsReq = {
        projectId: projectId,
        cityCodes,
        mediaTypes,
        strategySpecs: strategySpecs as unknown as strategySpecsItem[],
        businessScenario: 1,
        pointSelectionMode: isFromForgetting.value?3:0
    };
    showLoading();
    let res;
    try {
        res = await getStrategyStatistics(params);
        if(res){
            price.value = res.price;
            cph = res?.cph;
            faimaly.value = res.mediaResource?.resourceSummary?.coveredHouseholdNum || 0;
            people.value = res.mediaResource?.resourceSummary?.coveredPeopleNum || 0;
            screenPointNum.value = res.mediaResource?.mediaResourceSummaryList.find(item => item.mediaType === 1)?.pointNum || 0;
            lcdPointNum.value = res.mediaResource?.mediaResourceSummaryList.find(item => item.mediaType === 2)?.pointNum || 0;
        } else {
            resetData();
        }
    } catch (error) {
        console.log(error);
    } finally {
        clearLoading();
    }
}

async function strategyChange(mediaTypeList: MediaItem[], strategySpecsList:StrategyItemData[]) {
    mediaTypes = mediaTypeList.map(item => +item.value);
    strategySpecs = strategySpecsList;
    await getStrategyStatisticInfo();
}

async function changeCity(city:TreeChildModel[]) {
    cityCodes = city.map(item => item.tgCode || item.id);
    await getStrategyStatisticInfo();
}

const isCommunity = ref(true);
const onTabChange = (val: number) => {
    if(val === 1) {
        isCommunity.value = true;
    }
    if(val === 2) {
        isCommunity.value = false;
    }
};

const goBack = ()=>{
    router.back();
};
async function nextStep() {
    if(!isCommunity.value) {
        return;
    }
    if(!mediaTypes.length) {
        return Toast.fail('媒体形式至少选择一种');
    }
    if(+price.value === 0) {
        return Toast.fail('无楼盘资源');
    }
    showLoading();
    try {
        await saveStrategySpecs({
            projectId: projectId,
            cityCodes,
            mediaTypes,
            strategySpecs: strategySpecs as unknown as strategySpecsItem[],
            businessScenario: 1,
            pointSelectionMode: isFromForgetting.value?3:0
        });
        await router.push({name: 'productsBrandBreakoutResult', query: {
            type: isFromForgetting.value?6:3,
            isFromForgetting: +isFromForgetting.value
        }});
    } catch (error) {
        console.log(error);
    } finally {
        clearLoading();
    }
}

</script>

<style scoped lang="scss">
@import "@/styles/variables";

.mt12 {
    margin-top: 12px;
}
.page {
    background-color: #f4f4f4;
    height: 100vh;
    .content {
        padding: 12px 12px 160px;
    }
    .bottom {
        position: fixed;
        bottom: 0;
        background: #ffffff;
        width: 100%;
        border-top: 0.5px solid #f4f4f4;
        padding: 12px 0 8px;
        padding-bottom: contain(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
        overflow: hidden;
        box-sizing: border-box;
        box-shadow: 0 -2px 4px 0 #ebebeb80;

        div {
            display: flex;
            padding: 0 12px;

            span {
                display: inline-block;
                font-weight: 400;
                font-size: 12px;
                color: #5b5b5b;
                height: 17px;
            }
        }

        .bottom-text {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            text-align: right;
            .family-box {
                margin-bottom: 10px;
                font-weight: 500;
                font-size: 12px;
                color: #333333;
            }
            .total-amount {
                justify-content: flex-end;
                align-items: center;
                transform: translateX(8px);

                .amount {
                    height: 21px;
                    line-height: 21px;
                    font-family: $spec_font;
                    font-size: 18px;
                    color: #e60044;
                    text-align: right;
                }
                .remark {
                    height: 21px;
                    line-height: 21px;
                }
            }

            .cph-price {
                margin-top: 5px;
                transform: translateX(18px);
                justify-content: flex-end;
                align-items: center;

                .price {
                    height: 17px;
                    font-weight: 600;
                    font-size: 12px;
                    color: #333333;
                    margin-right: 6px;
                }

                img {
                    width: 14px;
                    height: 14px;
                }
            }
        }

        .fe-btns {
            margin-top: 12px;
            border-top: 0.5px solid #f4f4f4;
            display: flex;
            padding: 6px 12px 0;
            margin-bottom: 8px;

            div {
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .left {
                width: 120px;
                height: 38px;
                line-height: 38px;
                background: #ffffff;
                border: 0.5px solid #e60044;
                border-radius: 6px;
                font-weight: 400;
                font-size: 14px;
                color: #e60044;
                text-align: center;
                margin-right: 12px;
            }

            .right {
                width: calc(100% - 120px);
                height: 38px;
                line-height: 38px;
                background: #e60044;
                border: 0.5px solid #e60044;
                border-radius: 6px;
                font-weight: 600;
                font-size: 14px;
                color: #ffffff;
                text-align: center;
            }

            .disabled {
                background: #f06690;
            }
        }
    }
}
.pop-content {
    padding: 10px;
    font-size: 12px;
    line-height: 19px;
    width: 280px;
}
</style>
